package com.multipleThread.myRestaurant;

import com.multipleThread.p741.menu.Course;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 罗俊华
 * @date 2021/4/29 - 1:48 下午
 */
@Data
public class Customer implements Runnable {

    private static AtomicInteger count = new AtomicInteger();

    private int customerId;

    private static final Random RANDOM = new Random();

    private final Table table;

    private final RestaurantPlus restaurantPlus;

    public Customer(Table table, RestaurantPlus restaurantPlus) {
        assert table != null && restaurantPlus != null;
        this.table = table;
        this.restaurantPlus = restaurantPlus;
        this.customerId = count.getAndIncrement();
    }


    @Override
    public void run() {
        int foodCount = RANDOM.nextInt(3);

        for (int i = 0; i < foodCount; i++) {
            Food food = Food.getFood();
            try {
                WaitingPerson waitingPerson = this.restaurantPlus.getIdleWaitingPeople().take();

                System.out.printf("桌号【%d】的客人【%d】下单食物【%s】\n",this.table.getTableId(), customerId, food.getFoodName());

                waitingPerson.placeAnOrder(this, food);

                System.out.printf("桌号【%d】的客人【%d】等待食物【%s】\n",this.table.getTableId(), customerId, food.getFoodName());

                Plate plate = this.table.getNewFoodQueue().take();

                System.out.printf("桌号【%d】的客人【%d】拿到食物【%s】\n",this.table.getTableId(),customerId,plate.getFood().getFoodName());

            } catch (InterruptedException e) {
                e.printStackTrace();
                System.err.printf("桌号【%d】的客户[%d]在召唤服务员的时候被打断，客户此次想吃的食物是【%s】\n",this.table.getTableId(), customerId, food.getFoodName());
                return;
            }

        }
        /*for (Course course : Course.values()) {
            Food food = course.randomSelection();
            try {
                waitPerson.placeOrder(this, food);
                // Blocks until course has been delivered:
                System.out.println(this + "eating " + placeSetting.take());
            } catch (InterruptedException e) {
                System.out.println(this + "waiting for " +
                        course + " interrupted");
                break;
            }
        }
        System.out.println(this + "finished meal, leaving");*/
    }

}
